var LIB_INFO = {
    gMaps: {
	url: "http://maps.googleapis.com/maps/api/js?sensor=false&callback=initialize",
    },
    jUi: {
	url: "https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.min.js"
    },
    jUrl: {
	url: "/js/lib/jquery.url.js",
    },
    ddRoundies: {
	url: "/js/lib/DD_roundies_0.0.2a-min.js",
	callback: function() {
		DD_roundies.addRule('#navtop a', '10px');
	}
    },
    tranim: {
	url: "/js/pageAnim.js"
    },
    jBbq: {
	url: "/js/lib/jquery.ba-bbq.min.js"
    },
    homeSlideshow: {
	url: "/js/slideshow.js"
    },
    geoComplete: {
	url: "/js/lib/ui.geo_autocomplete.js"
    }
}

function withLibrary(name, callback) {
    if (!LIB_INFO[name])
	return;
    if (LIB_INFO[name].isLoading) {
	LIB_INFO[name].q.push(callback);
    }
    if (!LIB_INFO[name].isLoaded) {
	LIB_INFO[name].isLoading = true;
	LIB_INFO[name].q = new Array(
	    LIB_INFO[name].callback,
	    callback
	);
	$.getScript(LIB_INFO[name].url, function() {
	    $.each(LIB_INFO[name].q, function(index, value) {
		if (value) {
		    value();
		}
	    });
	    LIB_INFO[name].isLoaded = true;
	    LIB_INFO[name].isLoading = false;
	});
    }
    else {
	callback();
    }
}

PAGE_HOOKS = {
    loaded: {},
    pageLoaded: function(page) {
	page=page.substring(0, page.lastIndexOf("."));
	this.initHook(page);
	if (funk = this.loadFunk(page, "call")) { funk() };
    },
    loadFunk: function(page, hook) {
	if (PAGE_HOOKS[page] && PAGE_HOOKS[page][hook]) {
	    return PAGE_HOOKS[page][hook];
	};
	return null;
    },
    initHook: function(page) {
	if (!PAGE_HOOKS.loaded[page]) {
	    if (funk = this.loadFunk(page, "init")) { funk() };
	    PAGE_HOOKS.loaded.index = true;
	}
    },
    index: {
	call: function() {
	    withLibrary('homeSlideshow', function() {
		SLIDESHOW.start();
	    });
	},
    },
    locations: { call: loadLibLocations },
    "land/quincy": { call: loadLibLocations },
    "land/watertown": { call: loadLibLocations },
    "land/watertownt": {call: loadLibLocations }
}


function loadLibLocations() {
    withLibrary('gMaps', function() {
	$.getScript('/js/locations.js');
    });
}

var _gaq = _gaq || [];
_gaq.push([ '_setAccount', 'UA-24571871-1' ]);
_gaq.push([ '_trackPageview' ]);

$(function() {

    withLibrary('ddRoundies');
    withLibrary('jUrl', function() {
	if ($.url().attr('fragment') && $.url().attr('path') != "/"+$.url().attr('fragment')) {
	    window.location ="/"+$.url().attr('fragment');
	}
	var path = $.url().attr('path').substr(1);
	if ($.url().attr('path') == "/")
	    path = "index";
	PAGE_HOOKS.pageLoaded(path);
    });
    withLibrary('tranim');
    $.getScript('/js/hoursPopup.js');

    $.getScript('http://www.google-analytics.com/ga.js');

    $("<div id='loader'><img src='/images/ajax-loader.gif'/></div>").appendTo(
	"#contentPanel").hide();
});
